package com.tech.koufu.ui.activity.login;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.tech.koufu.MyApplication;
import com.tech.koufu.model.UserGroups;
import com.tech.koufu.tools.KouFuTools;
import com.tech.koufu.tools.SharedConfig;
import com.tech.koufu.tools.Statics;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.tencent.qq.QQ;
import android.app.Activity;
import android.content.Context;
import android.os.Handler.Callback;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
/**
 * 第三方登录(QQ)相关方法
 * @author jl_luo
 *
 */
public class BaseThridLoginActivity extends Activity implements Callback,PlatformActionListener {
	private static final String TAG = BaseThridLoginActivity.class.getName();
	private String userId;
	private String nickName;
	private StringRequest mRequest;
	private MyApplication myApp;
	private RequestQueue mQueue;
	private Context context;
	protected Platform qq ;
	@Override
	protected void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
		myApp = (MyApplication) getApplication();
		context = getApplicationContext();
		mQueue = Volley.newRequestQueue(context); 
	}
	
	@Override
	public void onCancel(Platform platform, int action) { 
		
	}

	@Override
	public void onComplete(Platform platform, int action, HashMap<String, Object> res) { 
		
	}

	@Override
	public void onError(Platform platform, int action, Throwable t) { 
		
	}

	@Override
	public boolean handleMessage(Message msg) { 
		return false;
	}
	protected boolean isThirdLogin(){ 
		return false;
	}

	protected void authorize(Platform plat){
		//判断指定平台是否已经完成授权
		if(plat.isValid()) {
			userId = plat.getDb().getUserId().substring(19, plat.getDb().getUserId().length());;
			nickName = plat.getDb().getUserName();
			if (userId != null) {  
				loginForQQ();
				return;
			}
		}
//		plat.setPlatformActionListener(this);
//		// true不使用SSO授权，false使用SSO授权
//		plat.SSOSetting(true);
//		//获取用户资料
//		plat.showUser(null);
	}
	private void loginForQQ(){
		String url = Statics.URL_PHP_vicp+Statics.register_fromQQ;//"http://cofweb1.vicp.net:16655/APP/register_fromQQ";

		mRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {

			private ArrayList<UserGroups> ugList;

			@Override
			public void onResponse(String response) { 
//				Log.v(TAG, "qq:"+response);
				if(response.substring(0, 1).equals("0")){
					try {
						ugList = new ArrayList<UserGroups>();
						JSONObject obj = new JSONObject(response.substring(2));
						if(obj.has("data")){
							JSONObject dobj = new JSONObject(obj.getString("data"));
							JSONArray ugArray = new JSONArray(dobj.getString("groups"));
							for(int i = 0 ; i < ugArray.length() ; i ++){
								UserGroups ug = new UserGroups(ugArray.getJSONObject(i));
								ugList.add(ug);
								if (ug.category == 1) {
									myApp.setUserid(ugList.get(i).group_id + "X" + dobj.getInt("digitalid"));
									myApp.setUserName(dobj.getString("userName"));
									myApp.setGroupId(""+ugList.get(i).group_id);
									myApp.setDigitalid(""+dobj.getInt("digitalid"));
//									myApp.setUserpwd(ed_userpwd.getText().toString().trim());
									myApp.url = KouFuTools.UrlChoose(ugList.get(i).web_id);
									myApp.isLogin = true; 
								}
							} 
//							Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show();
							SharedConfig.setLoginStatus(getApplicationContext(), nickName, 
									userId,System.currentTimeMillis(),"qq"); 
						}
					} catch (JSONException e) { 
						e.printStackTrace();
					}
				}
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				error.printStackTrace();
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>();
				params.put("id", userId);
				params.put("nickname", nickName);
				return params;
			}
			@Override
			protected Response<String> parseNetworkResponse(
					NetworkResponse response) {
				try { 
					Map<String, String> responseHeaders = response.headers;
//					Log.d(TAG, "qq:"+responseHeaders.toString());
					String rawCookies = responseHeaders.get("Set-Cookie");  
					myApp.phpsessid = rawCookies; 
					String dataString = new String(response.data, "UTF-8"); 
					return Response.success(dataString,HttpHeaderParser.parseCacheHeaders(response));
				} catch (UnsupportedEncodingException e) {
					return Response.error(new ParseError(e));
				} 
				 
			}
		};
		mQueue.add(mRequest);
	}
	protected void toLogin(final String user,final String pwd){ 
		String url = Statics.URL_PHP+"login"; 
		mRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {

			@Override
			public void onResponse(String response) { 
				try {Log.d(TAG,response);
					if(!TextUtils.isEmpty(response)){
						ArrayList<UserGroups> ugList = new ArrayList<UserGroups>();
						JSONObject obj = new JSONObject(response.substring(2));
						if(response.substring(0, 1).equals("0")){
							JSONObject dataObj = new JSONObject(obj.getString("data"));
							JSONArray ugArray = new JSONArray(dataObj.getString("groups"));
							for(int i = 0 ; i < ugArray.length() ; i ++){
								UserGroups ug = new UserGroups(ugArray.getJSONObject(i));
								ugList.add(ug);
								if (ug.category == 1) {
									myApp.setUserid(ugList.get(i).group_id + "X" + dataObj.getInt("digitalid"));
									myApp.setUserName(dataObj.getString("userName"));
									myApp.setGroupId(""+ugList.get(i).group_id);
									myApp.setDigitalid(""+dataObj.getInt("digitalid"));
									myApp.setUserpwd(pwd);
									myApp.url = KouFuTools.UrlChoose(ugList.get(i).web_id);
									myApp.isLogin = true; 
								}
							}Log.d(TAG,"islogin = "+myApp.isLogin);
							SharedConfig.setLoginStatus(getApplicationContext(), user, pwd,System.currentTimeMillis(),"sn");  
						} 
					} 
				} catch (JSONException e) { 
					e.printStackTrace();
				}

			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {  
			}
		}){

			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> params = new HashMap<String, String>();
				params.put("userid", user);
				params.put("password", pwd); 
				return params;
			}		
			@Override
			protected Response<String> parseNetworkResponse(
					NetworkResponse response) {
				try { 
					Map<String, String> responseHeaders = response.headers;
					String rawCookies = responseHeaders.get("Set-Cookie");  
					myApp.phpsessid = rawCookies; 
					String dataString = new String(response.data, "UTF-8"); 
					return Response.success(dataString,HttpHeaderParser.parseCacheHeaders(response));
				} catch (UnsupportedEncodingException e) {
					return Response.error(new ParseError(e));
				} 
				 
			}
		};
		mQueue.add(mRequest);
	}
}
